{% extends 'base_backend.html' %}
{% load static %}
{% load my_filter %}

{% block header_tail %}
    <link rel="stylesheet" href="{% static 'zhongbao/zhongbao_admin/css/style.css' %}">
    <link rel="stylesheet" href="{% static 'zhongbao/zhongbao_admin/css/iconfont.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/datatables/dataTables.bootstrap.css' %}">
    <link rel="stylesheet" href="{% static 'public/ComboSelect/css/combo.select.css' %}">
    <link rel="stylesheet" href="{% static 'zhongbao/config/css/main.css' %}">
    <script src="{% static 'plugins\jQuery\jquery-2.2.3.min.js' %}"></script>

    <script src="{% static 'plugins/vue1/vue.js' %}"></script>

    <style>
        .login-banner {
            width: 100%;
            background: url("{% static 'public/img/banner2.jpg' %}") center bottom/cover no-repeat;
        }
    </style>
{% endblock header_tail %}

{% block section_content %}
    <div>
        <div class="box-header with-border">
            <h3 class="box-title">{{ model_verbose_name }}</h3>
        </div>
        <!-- form start -->
        <div class="box box-primary">
        <div class="box-header with-border" style="border-color: #1b6d85">

                <!-- Date range -->
                <form role="form" id="searchForm">
                    <input class="no-display" type="text">
                    <p style="clear: both"></p>
                    <div>
                        <div style="float: left;" class="input-group select-config-div">
                            <label for="id" class="control-label">任务ID：</label>
                            <p>
                                <input id="taskId" name="task_id" type="text" class="config-input">
                            </p>

                        </div>
                        {% for field in form %}
                            <div class="input-group select-config-div" style="float: left; ">
                                <label for="" class="control-label">{{ field.label }}：</label>
                                <p>{{ field }}</p>
                            </div>
                        {% endfor %}
                        <div style="float: left;" class="input-group select-config-div">
                            <label for="id" class="control-label">任务状态：</label>
                            <select name="status" id="taskStatus" class="config-input">
                                {% for filter in filters %}
                                    {% if filter.status == 0 %}
                                        <option selected="selected" value="{{ filter.status }}">{{ filter.name }}</option>
                                    {% else %}
                                        <option value="{{ filter.status }}">{{ filter.name }}</option>
                                    {% endif %}
                                {% endfor %}
                            </select>
                        </div>
                        <div style="float: left;" class="input-group select-config-div">
                            <label for="id" class="control-label">每页显示：</label>
                            <select name="limit" id="showNumSelect" class="config-input">
                                {% for i in limits %}
                                    {% if i == limit %}
                                        <option selected="selected" value="{{ i }}">{{ i }}条</option>
                                    {% else %}
                                        <option value="{{ i }}">{{ i }}条</option>
                                    {% endif %}
                                {% endfor %}
                            </select>
                        </div>
                        <div class="input-group" style=";float: right">
                            <input type="text" class="no-display">
                            <span id="searchBtn" onclick="searchTasks()" class="form-control pull-left btn btn-sm btn-primary"
                                    style="margin-top:20px;width: 50px">检索
                            </span>
                        </div>
                    </div>
                    <p style="clear: both"></p>
                    <div class="form-group">
                    </div>
                </form>
            </div>
        <!--
            <div class="box-header with-border" style="border-color: #1b6d85">
            </div>
            <div id="ItemsTree" style="position:absolute;left:200px;top:90px; display:none;width:250px;height:300px;border:dashed 1px #000000; background-color:#F7F7F7; overflow:auto"></div>
        -->
        <!-- 展示搜索出来的任务 -->
            <div id="main">
                <div id="showMessage" v-show="message"> [[ message ]]</div>
                <div class="box-body" v-show="showMain">
                    <form id="model_form" role="form"
                          method="post">{% csrf_token %}
                        <div class="group">
                        <!--
                            {/% for action in actions %}
                                {/% if action.status == 1 %}
                                    <button style="margin-right:20px;" type="button" class="btn btn-primary btn-xs" disabled="true" status="{/{ action.status }}" onclick="allocateTasks(this)">{/{ action.name }}</button>
                                {/% else %}
                                    <button style="margin-right:20px;" type="button" class="btn btn-primary btn-xs" status="{/{ action.status }}" onclick="allocateTasks(this)">{/{ action.name }}</button>
                                {/% endif %}
                            {/% endfor %}
                            -->
                            <a style="margin-right:20px;" type="button" class="btn btn-primary btn-xs" href="{% url 'task:allocate' %}">任务分配专区</a>
                            <a style="margin-right:20px;" type="button" class="btn btn-primary btn-xs" href="{% url 'task:retrieve' %}">任务回收专区</a>
                            <a style="margin-right:20px;" type="button" class="btn btn-primary btn-xs" href="{% url 'task:check' %}">任务审核专区</a>
                            <table id="task_each_table" border="1" class="table table-bordered table-hover table-striped">
                                <thead>
                                <tr>
                                    <th v-for="head in tableData.headers">
                                        <span style="float: left">
                                            [[ head.name ]]
                                        </span>
                                        {% if field.rank %}
                                            <a href="?[[ head.rank ]]=[[ head.rank_tag ]][[ page_args ]]"
                                               style="float: right">
                                                {% if field.rank_tag == 0 %}
                                                    <i class="fa fa-fw fa-sort"></i>
                                                {% elif field.rank_tag == 1 %}
                                                    <i class="fa fa-fw fa-sort-numeric-asc"></i>
                                                {% elif field.rank_tag == -1 %}
                                                    <i class="fa fa-fw fa-sort-numeric-desc"></i>
                                                {% endif %}
                                            </a>
                                        {% endif %}
                                    </th>
                                    <th>
                                        <span style="float: left">
                                            操作
                                        </span>
                                    </th>
                                </tr>
                                </thead>
                                <tbody>
                                    <template v-for="task in tableData.tasks">
                                        <!--<tr v-if="task.allocation_flag">-->
                                        <tr>
                                            <td v-for="head in tableData.headers">[[ task[head.key] ]]</td>
                                            <td class="btn-group">
                                                <button v-if="task.status > 1" type="button" value="[[ task.id ]]" class="btn btn-info btn-xs" onclick="retrieveOneTask([[task.id]])">回收</button>
                                                <button v-else type="button" value="[[ task.id ]]" class="btn btn-info btn-xs" onclick="allocateOneTask([[task.id]])">分配</button>
                                                <button v-if="task.status == 4" type="button" value="[[ task.id ]]" class="btn btn-info btn-xs" onclick="detailOneTask([[task.id]],[[task.status]])">审核</button>
                                                <button type="button" value="[[ task.id ]]" class="btn btn-info btn-xs" onclick="detailOneTask([[task.id]],[[task.status]])">详情</button>
                                            </td>
                                        </tr>
                                        <!--
                                        <tr v-else style="background-color:#ff9e9e">
                                            <td class="action-checkbox">
                                                <input type="checkbox" name="td_checkbox" value="task.id" onclick="checkOne(this)">
                                            </td>
                                            <td v-for="head in tableData.headers">[[ task[head.key] ]]</td>
                                            <td class="btn-group">
                                                <button v-if="task.allocation_flag" type="button" class="btn btn-info btn-xs" value="task.id">收回</button>
                                                <button v-else type="button" class="btn btn-info btn-xs" value="task.id" onclick="showUsers()">分派</button>
                                                <button type="button" class="btn btn-info btn-xs" value="task.id">删除</button>
                                            </td>
                                        </tr>
                                        -->
                                    </template>
                                </tbody>
                            </table>
                            <p class="" id="paginator">
                                <a class="btn btn-default btn-xs" v-if="paginator.current > 1" onclick="toPage('first',paginator.limit)">首页</a>
                                <a class="btn btn-default btn-xs" v-else disabled="true">首页</a>
                                <a class="btn btn-default btn-xs" v-if="paginator.current > 1" onclick="toPage('prev',paginator.limit)">上一页</a>
                                Page [[ paginator.current ]] of [[ paginator.last ]]
                                <a class="btn btn-default btn-xs" v-if="paginator.current < paginator.last" onclick="toPage('next',paginator.limit)">下一页</a>
                                <a class="btn btn-default btn-xs" v-if="paginator.current < paginator.last" onclick="toPage('last',paginator.limit)">尾页</a>
                                <a class="btn btn-default btn-xs" v-else disabled="true">尾页</a>
                                <input type="text" id="page-judge" style="width: 30px;height:20px; margin-left: 20px">
                                <a class="btn btn-default btn-xs"  onclick="toPage('judge', paginator.limit)">跳页</a>
                            </p>
                        </div>
                        <!-- /.box-footer -->
                        <div class="box-footer">
                            <button class="btn btn-primary no-display" id="submit_button">确认</button>
                            <button type="button" class="btn btn-primary" id="save_submit" name="_save"
                                    style="display: none">sure
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="cancel-window" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" style="top:30%">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body" style="overflow:auto">
                    <!--
                    <label>请选择要分配给谁（可以多选）：</label>
                    {/% for user in configUsers %}
                        <br><input name="user" type="radio" value="{/{ user.user.id }}">
                        <label>{/{ user.user.username }}</label>
                    {/% endfor %}
                    -->
                    <!--
                    <table id="user_each_table" border="1" class="table table-bordered table-hover table-striped">
                        <thead>
                            <tr>
                                <th class="action-checkbox">
                                    <input type="checkbox" name="uth_checkbox" onclick="_checkAll(this)">
                                </th>
                                <th>
                                    <span style="float: left">
                                        用户名
                                    </span>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {/% for user in configUsers %}
                                <br>
                                <tr>
                                    <td class="action-checkbox">
                                        <input type="checkbox" name="utd_checkbox" value="{/{ user.user.id }}" onclick="_checkOne(this)">
                                    </td>
                                    <td>{/{ user.user.username }}</td>
                                </tr>
                            {/% endfor %}
                        </tbody>
                    </table>
                    -->
                    <label>请选择要分配给谁：</label>
                    <input id="task_Id" value="" style="display:none;">
                    <table id="user_each_table" border="1" class="table table-bordered table-hover table-striped">
                        <thead>
                            <tr>
                                <th class="action-checkbox">
                                    #
                                </th>
                                <th>
                                    <span style="float: left">
                                        用户名
                                    </span>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for user in configUsers %}
                                <br>
                                <tr>
                                    <td class="action-checkbox">
                                        <input type="radio" name="utd_checkbox" value="{{ user.user.id }}">
                                    </td>
                                    <td>{{ user.user.username }}</td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" id="confirm_close" class="btn btn-default"
                            data-dismiss="modal" onclick="confirmClose()">确认
                    </button>
                    <button type="button" id="cancel_close" class="btn btn-default"
                            data-dismiss="modal" onclick="cancelClose()">取消
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function retrieve(tids){
            if (!tids){
                var _tids = [];
                $("input[name='td_checkbox']:checked").each(
                    function(){
                        _tids.push($(this).val())
                    }
                );
                tids = _tids.join();
            }
            if (tids.length === 0){
                return false
            }else{
                $.ajaxSetup({
                    data:{
                        csrfmiddlewaretoken:'{{ csrf_token }}',
                        tids: tids
                    }
                });
                $.post(
                    "{% url 'task:retrieve' %}",
                    function(response){
                        console.log(response);
                        mainVue.message = response.message;
                        toPage('current')
                    }
                )
            }
        }

        function retrieveOneTask(tids){
            retrieve(tids)
        }
        function allocate(tids, uids){
            if (!tids){
                var _tids = [];
                $("input[name='td_checkbox']:checked").each(
                    function(){
                        _tids.push($(this).val())
                    }
                );
                tids = _tids.join();
            }
            if (!uids){
                var _uids = [];
                $("input[name='utd_checkbox']:checked").each(
                    function(){
                        _uids.push($(this).val())
                    }
                );
                uids = _uids.join();
            }
            if ((tids.length === 0) || (uids.length === 0)){
                return false
            }else{
                $.ajaxSetup({
                    data:{
                        csrfmiddlewaretoken:'{{ csrf_token }}',
                        tids: tids,
                        uids: uids
                    }
                });
                $.post(
                    "{% url 'task:allocate' %}",
                    function(response){
                        console.log(response);
                        mainVue.message = response.message;
                        toPage('current')
                    }
                )
            }
        }

        function allocateOneTask(tids){
            $("#task_Id").val(tids);
            showUsers()
        }
        function detailOneTask(id, status){
           var url = "{% url 'task:detail' %}" + "?id=" + id + "&status=" + status;
           window.location.href = url;
        }

        function confirmClose(){
            var uids = [];
            $("input[name='utd_checkbox']:checked").each(
                function(){
                    uids.push($(this).val());
                }
            );
            uids = uids.join();
            var tids = $("#task_Id").val();
            console.log(tids, uids);
            if (uids.length === 0 || tids.length === 0){
                return false
            }else{
                allocate(tids, uids);
                toPage("current")
            }
        }
        function cancelClose(){
            _clearChecked();
        }
        function _clearChecked(){
            if ($("input[name='uth_checkbox']").is(":checked")){
                $("input[name='uth_checkbox']").prop("checked", false)
            }
            $("input[name='utd_checkbox']:checked").each(
                function(){
                    $(this).prop("checked", false);
                }
            );
        }
        function allocateTasks(){
            showUsers();
        }
        function showUsers(){
            var cancel_window = $("#cancel-window");
            cancel_window.modal()
        }
        function checkAll(obj){
            if ($(obj).is(":checked")){
                $("input[name='td_checkbox']").prop("checked", true)
            }else{
                $("input[name='td_checkbox']").prop("checked", false)
            }

        }
        function checkOne(obj){
            if ($("input[name='th_checkbox']").is(":checked")){
                $("input[name='th_checkbox']").prop("checked", false)
            }else{
                var unChecked = 0;
                $("input[name='td_checkbox']").each(
                    function(){
                        if ($(this).is(":checked")){

                        }else{
                            unChecked += 1
                        }
                    }
                );
                if (unChecked === 0){
                    $("input[name='th_checkbox']").prop("checked", true)
                }
            }
        }
        function _checkAll(obj){
            if ($(obj).is(":checked")){
                $("input[name='utd_checkbox']").prop("checked", true)
            }else{
                $("input[name='utd_checkbox']").prop("checked", false)
            }

        }
        function _checkOne(obj){
            if ($("input[name='uth_checkbox']").is(":checked")){
                $("input[name='uth_checkbox']").prop("checked", false)
            }else{
                var unChecked = 0;
                $("input[name='utd_checkbox']").each(
                    function(){
                        if ($(this).is(":checked")){

                        }else{
                            unChecked += 1
                        }
                    }
                );
                if (unChecked === 0){
                    $("input[name='uth_checkbox']").prop("checked", true)
                }
            }
        }
        Vue.config.delimiters = ["[[", "]]"];

        function filterTasks(obj){
            var checkedAll = $('input[name="th_checkbox"]');
            if (checkedAll.is(":checked")){
                checkedAll.prop("checked", false);
            }
            var page = 1;
            var status = parseInt($(obj).attr("status"));
            var limit = parseInt($("#showNumSelect").val());
            $(obj).attr("disabled", true);
            var $disabledBtn = $(obj).siblings().attr("disabled",true);
            $disabledBtn.attr("disabled",false);
            //console.log(page,status,limit);
            mainVue.page = page;
            mainVue.limit = limit;
            mainVue.status = status;
            mainVue.checkedAll = false;
            render(mainVue);
        }


        function toPage(page){
            if (mainVue.paginator){
                if (page == 'current'){
                    page = mainVue.paginator.current
                }
                if (page == 'next'){
                    page = mainVue.paginator.current + 1
                }
                if (page == 'prev'){
                    page = mainVue.paginator.current - 1
                }
                if (page == 'first'){
                    page = 1
                }
                if (page == 'last'){
                    page = mainVue.paginator.last
                }
                if (page == 'judge'){
                    page = $("#page-judge").val();
                }
                if (page < 1) {
                    page = 1;
                }
                if (page > mainVue.paginator.last){
                    page = mainVue.paginator.last;
                }
                if (page < mainVue.paginator.first){
                    page = mainVue.paginator.first;
                }
            }else{
                page = 1;
            }
            mainVue.page = page;
            render(mainVue);
        }

        function render(obj){
            var searchForm = obj.searchForm + '&page=' + obj.page;
            $.get(
                "{% url 'task:filter_tasks' %}",
                searchForm,
                function(response){
                    if (response){
                        obj.showMain = true;
                        obj.tableData = response.tableData;
                        obj.paginator = response.paginator;
                        obj.message = response.message;
                        console.log(obj.paginator);
                    }else{
                        obj.showMain = false;
                    }
                }
            )
        }
        var mainVue = new Vue({
            el: "#main",
            data: {
                page: 1,
                status: 1,
                limit: {{ limit }},
                searchForm: "",
                checkedAll: false,
                showMain: false,
                tableData: {},
                paginator: {},
                message: ""
            },
            methods: {
                //searchTasks: searchTasks,
                getTasks: function(){
                    var searchForm = 'page=' + this.page + '&limit=' + this.limit + '&status=' + this.status;
                    $.get(
                        "{% url 'task:filter_tasks' %}",
                        searchForm,
                        function(response){
                            if (response){
                                this.showMain = true;
                                this.tableData = response.tableData;
                                this.paginator = response.paginator;
                                this.message = response.message;
                                console.log(this.paginator);
                            }else{
                                this.showMain = false;
                            }
                        }
                    )
                }
            },
            watch: {
{#                page: function(){#}
{#                    render(this);#}
{#                }#}
            }
        });
        function searchTasks(){
            mainVue.searchForm = $("#searchForm").serialize();
            $.get(
                "{% url 'task:filter_tasks' %}",
                mainVue.searchForm,
                function(response){
                    if (response){
                        mainVue.limit = response.limit;
                        mainVue.showMain = true;
                        mainVue.limits = response.limits;
                        mainVue.tableData = response.tableData;
                        mainVue.paginator = response.paginator;
                        mainVue.message = response.message;
                    }else{
                        mainVue.showMain = false;
                    }
                }
            )
        }
        searchTasks();
        //when page onload, init the table.
        //render(mainVue);
    </script>
{% endblock section_content %}
